import os
from datetime import datetime, timedelta
import okx.MarketData as MarketData
import pandas as pd
import pytz

# 登录信息
api_key = "c3e58aef-d146-4458-9e62-b1d12073e5be"
secret_key = "B71758AA67EE4431D844AA224B0B9094"
passphrase = "Tyq@1997"
flag = "0"  # live trading: 0, demo trading: 1

marketDataAPI = MarketData.MarketAPI(flag=flag)


# 获取指定日期前100天日k线数据
def get_100d_candlesticks(date=datetime.now()):
    date_0 = int(date.timestamp()) * 1000
    date_100 = int((date - timedelta(days=101)).timestamp()) * 1000

    # 通过okx的api拉取历史k线数据并做简单处理
    candlesticks = \
        marketDataAPI.get_history_candlesticks(instId='BTC-USDT', after=date_0, before=date_100, bar='1D',
                                               limit='')['data']
    price_candlesticks = pd.DataFrame(candlesticks,
                                      columns=['openTime', 'openPrice', 'highestPrice', 'lowestPrice', 'closePrice',
                                               'vol',
                                               'vol-USDT', 'volCcyQuote', 'complete'])
    price_candlesticks['openTime'] = pd.to_numeric(price_candlesticks['openTime'], errors='coerce')
    price_candlesticks['openPrice'] = pd.to_numeric(price_candlesticks['openPrice'], errors='coerce').fillna(0).round(4)
    price_candlesticks['highestPrice'] = pd.to_numeric(price_candlesticks['highestPrice'], errors='coerce').fillna(
        0).round(4)
    price_candlesticks['lowestPrice'] = pd.to_numeric(price_candlesticks['lowestPrice'], errors='coerce').fillna(
        0).round(4)
    price_candlesticks['closePrice'] = pd.to_numeric(price_candlesticks['closePrice'], errors='coerce').fillna(0).round(
        4)
    price_candlesticks['vol'] = pd.to_numeric(price_candlesticks['vol'], errors='coerce').fillna(0).round(4)
    price_candlesticks['vol-USDT'] = pd.to_numeric(price_candlesticks['vol-USDT'], errors='coerce').fillna(0).round(
        4)
    price_candlesticks['volCcyQuote'] = pd.to_numeric(price_candlesticks['volCcyQuote'], errors='coerce').fillna(
        0).round(4)
    price_candlesticks['complete'] = pd.to_numeric(price_candlesticks['complete'], errors='coerce').fillna(0).round(4)

    price_candlesticks['openTime'] = pd.to_datetime(price_candlesticks['openTime'], unit='ms')
    price_candlesticks['openTime'] = price_candlesticks['openTime'].dt.tz_localize(pytz.utc)
    price_candlesticks['openTime'] = price_candlesticks['openTime'].dt.tz_convert(pytz.timezone('Asia/Shanghai'))
    price_candlesticks['openTime'] = price_candlesticks['openTime'].dt.strftime('%Y-%m-%d %H:%M:%S')

    price_candlesticks['long_shadow'] = None
    price_candlesticks['ph_line'] = None
    price_candlesticks['cross'] = None

    return price_candlesticks


# 连续获取n个100天的数据
def get_his_candl(date, page):
    # 指定excel路径
    df_his = pd.DataFrame()
    for i in range(page):
        date = date - timedelta(days=100 * i)
        get_100d_candlesticks(date)
        df_his = pd.concat([df_his, get_100d_candlesticks(date)])
    return df_his


# 计算long_shadow
date_1017 = datetime.now() - timedelta(days=3)
df_candl = get_his_candl(date_1017, 5)
df_candl.reset_index(drop=True, inplace=True)
for row in df_candl.itertuples():
    # 误差值：
    tolerance = row.closePrice * 0.005
    # 计算k线总长、影线、实体
    upper_shadow = row.highestPrice - max(row.openPrice, row.closePrice)
    price_range_total = row.highestPrice - row.lowestPrice
    true_range = abs(row.openPrice - row.closePrice)
    down_shadow = min(row.openPrice, row.closePrice) - row.lowestPrice
    if row.Index < 492:
        # 前日k线总长、影线、实体
        upper_shadow_a = df_candl.at[row.Index + 1, 'highestPrice'] - max(df_candl.at[row.Index + 1, 'openPrice']
                                                                          , df_candl.at[row.Index + 1, 'closePrice'])
        price_range_total_a = df_candl.at[row.Index + 1, 'highestPrice'] - df_candl.at[row.Index + 1, 'lowestPrice']
        true_range_a = abs(df_candl.at[row.Index + 1, 'openPrice'] - df_candl.at[row.Index + 1, 'closePrice'])
        down_shadow_a = min(df_candl.at[row.Index + 1, 'openPrice'], df_candl.at[row.Index + 1, 'closePrice']) - \
                        df_candl.at[row.Index + 1, 'lowestPrice']

        # 设定一个阈值比例来判断长上影线，例如上影线长度超过整个价格范围的10%
        threshold_ratio = 0.4
        # day_change = 3
        # change_ratio = 0.03
        # 倒锤头
        if upper_shadow > threshold_ratio * price_range_total \
                and down_shadow < price_range_total * 0.1 and price_range_total / row.closePrice >= 0.04:
            # if (max(df_candl.at[row.Index + day_change, 'openPrice'], df_candl.at[
            #     row.Index + day_change, 'closePrice']) - row.closePrice) / row.closePrice > change_ratio:
            #     df_candl.at[row.Index, 'long_shadow'] = 1
            # elif (max(df_candl.at[row.Index + day_change, 'openPrice'], df_candl.at[
            #     row.Index + day_change, 'closePrice']) - row.closePrice) / df_candl.at[
            #     row.Index + day_change, 'closePrice'] < -change_ratio:
            df_candl.at[row.Index, 'long_shadow'] = 1
        # 锤头
        elif down_shadow > threshold_ratio * price_range_total \
                and upper_shadow < price_range_total * 0.1 and price_range_total / row.closePrice >= 0.04:
            # if (row.closePrice - min(df_candl.at[row.Index + day_change, 'openPrice'], df_candl.at[
            #     row.Index + day_change, 'closePrice'])) / row.closePrice > change_ratio:
            #     df_candl.at[row.Index, 'long_shadow'] = -1
            # elif (row.closePrice - min(df_candl.at[row.Index + day_change, 'openPrice'], df_candl.at[
            #     row.Index + day_change, 'closePrice'])) / df_candl.at[
            #     row.Index + day_change, 'closePrice'] < -change_ratio:
            df_candl.at[row.Index, 'long_shadow'] = 1

        # 阳抱线 or 阳孕线
        if row.closePrice >= df_candl.at[row.Index + 1, 'openPrice'] - tolerance >= df_candl.at[
            row.Index + 1, 'closePrice'] >= row.openPrice - tolerance and true_range / row.closePrice >= 0.03:
            df_candl.at[row.Index, 'ph_line'] = 1
            print(row.Index)
            print(row.openTime)
            print(true_range_a)
            print(true_range)
        elif df_candl.at[
            row.Index + 1, 'openPrice'] >= row.closePrice - tolerance >= row.openPrice >= df_candl.at[
            row.Index + 1, 'closePrice'] - tolerance and true_range_a / df_candl.at[
            row.Index + 1, 'closePrice'] >= 0.03:
            df_candl.at[row.Index, 'ph_line'] = 1

max_rows = []
long_shadow_1 = df_candl[df_candl['long_shadow'] == 1].index.tolist()
for i in range(len(long_shadow_1)):
    date = df_candl.at[long_shadow_1[i], 'openTime']
    end_index = min(long_shadow_1[i] + 1, len(df_candl))
    start_index = max(0, end_index - 7)
    slice_df = df_candl.iloc[start_index:end_index]
    max_row = slice_df.loc[slice_df['closePrice'].idxmax()]  # 直接找到最大值所在的行
    new_row = {
        'k_line': 'long_shadow_1',
        'date': date,
        'max_value': max_row['closePrice'],
        'max_date': max_row['openTime'],
        'growth': (max_row['closePrice'] - df_candl.at[long_shadow_1[i], 'closePrice']) / df_candl.at[
            long_shadow_1[i], 'closePrice']
    }
    max_rows.append(new_row)

long_shadow_0 = df_candl[df_candl['long_shadow'] == -1].index.tolist()
print("-" * 50)
print(long_shadow_0)
for i in range(len(long_shadow_0)):
    date = df_candl.at[long_shadow_0[i], 'openTime']
    end_index = min(long_shadow_0[i] + 1, len(df_candl))
    start_index = max(0, end_index - 7)
    slice_df = df_candl.iloc[start_index:end_index]
    max_row = slice_df.loc[slice_df['closePrice'].idxmin()]  # 直接找到最小值所在的行
    new_row = {
        'k_line': 'long_shadow_0',
        'date': date,
        'max_value': max_row['closePrice'],
        'max_date': max_row['openTime'],
        'growth': (max_row['closePrice'] - df_candl.at[long_shadow_1[i], 'closePrice']) / df_candl.at[
            long_shadow_1[i], 'closePrice']
    }
    max_rows.append(new_row)

max_rows = pd.DataFrame(max_rows)
df_candl = pd.concat([df_candl, max_rows], ignore_index=True)

print(max_rows)
print(max_rows['growth'].mean())
excel_path = r'C:\Users\guozh\Desktop\信息技术\btc.xlsx'
df_candl.to_excel(excel_path, index=True)
